﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Main.cs" company="Scrum for Team System">
//   None
// </copyright>
// <summary>
//   Defines the Main type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Bootstrapper
{
    using System;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;

    using WindowsInstaller;
    
    public partial class Main : Form
    {
        private string logFilePath;
        private string msiFilePath;

        public Main(string PathToMsi)
        {
            InitializeComponent();

            this.msiFilePath = PathToMsi;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            setDefaultValues();
        }
        private void txtTfsWebSitePort_TextChanged(object sender, EventArgs e)
        {
            updateEventServiceUrl();
        }
        private void btnInstall_Click(object sender, EventArgs e)
        {
            if (validateParameters())
            {
                this.Hide();

                MsiError res = installMsi();

                this.Close();
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void chkTfsAppTier_CheckedChanged(object sender, EventArgs e)
        {
            txtTfsWebSiteDescription.Enabled = chkTfsAppTier.Checked;
            txtTfsWebSitePort.Enabled = chkTfsAppTier.Checked;
            txtSftsEventServiceUrl.Enabled = chkTfsAppTier.Checked;
        }
        private void chkReportingServices_CheckedChanged(object sender, EventArgs e)
        {
            txtSsrsInstanceName.Enabled = chkReportingServices.Checked;
        }
        private void chkSharePoint_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void setDefaultValues()
        {
            this.Text = "Scrum for Team System v3 Setup";
            this.txtTfsWebSiteDescription.Text = "Team Foundation Server";
            this.txtTfsWebSitePort.Text = "8080";
            this.txtSsrsInstanceName.Text = "ReportServer";

            chkTfsAppTier.Checked = true;
            chkReportingServices.Checked = true;
            chkSharePoint.Checked = true;

            this.btnInstall.Focus();
        }
        private bool updateEventServiceUrl()
        {
            try
            {
                string derivedUrl = string.Format("http://localhost:{0}/ScrumForTeamSystem/3.0/WorkItemChangedEndpoint.asmx", this.txtTfsWebSitePort.Text);
                new Uri(derivedUrl);

                this.txtSftsEventServiceUrl.Text = string.Format("http://localhost:{0}/ScrumForTeamSystem/3.0/WorkItemChangedEndpoint.asmx", this.txtTfsWebSitePort.Text);
                this.txtSftsEventServiceUrl.SelectedText = String.Empty;
                this.txtSftsEventServiceUrl.SelectionStart = this.txtSftsEventServiceUrl.Text.Length;
                this.txtSftsEventServiceUrl.Refresh();
            }
            catch (UriFormatException)
            {
                MessageBox.Show("Please enter a valid port number for the 'TFS Web Site Port' field." + Environment.NewLine + "(Valid values are 1-65535)", "Invalid Port Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            return true;
        }
        private bool validateParameters()
        {
            if (chkTfsAppTier.Checked)
            {
                // Make sure the EventServiceURL is up-to-date and valid
                return updateEventServiceUrl();
            }

            return true;
        }
        private MsiError installMsi()
        {
            // build command-line to install the MSI
            string msiParameters = buildMsiParameters();
            System.Diagnostics.Trace.WriteLine("SFTS_MSIParameters: " + msiParameters);

            // Enable logging
            MsiInterop.MsiEnableLog(MsiInstallLogMode.Verbose, this.generateLogFilename(), MsiLogAttribute.FlushEachLine);

            // Enable the UI
            IntPtr parent = this.Handle;
            MsiInterop.MsiSetInternalUI(MsiInstallUILevel.Full, ref parent);

            // GO!
            MsiError res = MsiInterop.MsiInstallProduct(this.msiFilePath, msiParameters);
            
            return res;
        }
        private string buildMsiParameters()
        {
            var sb = new StringBuilder();

            sb.AppendFormat("{0}=\"{1}\" ", Constants.MsiProp_TFS_WebSite_Description, this.txtTfsWebSiteDescription.Text);
            sb.AppendFormat("{0}=\"{1}\" ", Constants.MsiProp_TFS_WebSite_Port, this.txtTfsWebSitePort.Text);
            sb.AppendFormat("{0}=\"{1}\" ", Constants.MsiProp_SSRS_InstanceName, this.txtSsrsInstanceName.Text);
            sb.AppendFormat("{0}=\"{1}\" ", Constants.MsiProp_SFTS_EventServiceURL, this.txtSftsEventServiceUrl.Text);

            return sb.ToString();
        }
        private string generateLogFilename()
        {
            string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            string logfile = string.Format("SFTS3_Install_{0}.log", timestamp);
            this.logFilePath = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), logfile);

#if DEBUG
            MessageBox.Show("LogFile: " + this.logFilePath);
#endif

            return this.logFilePath;
        }
    }
}
